import React from 'react';
import { Layout, Breadcrumb, Icon, Tag, Button, Table, Checkbox, Input, Select, Form, Pagination, message, TreeSelect } from 'antd';
import { Link } from 'react-router';
import './allgoods.less';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token')

class RegForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false, //菜单折叠状态
            mode: 'inline', //菜单显示模式，垂直 or 行内
            productlist: [],//全部商品列表
            productcount: 0,//全部商品条数
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            Inkey: undefined,//关键字
            isdrugstatus: undefined,//类别
            iscoldstorage: undefined,//冷藏
            isspecialdrug: undefined,//特管
            salestatus: undefined,//状态
            selectproductid: [],//选中的商品ID
            categoryid: undefined,//分类
            categoryData: [], //所有分类
            brandList: [],   //品牌列表
            brandListid: undefined,//品牌
        }
    }

    componentDidMount() {
        const data = this.props.location.state;
        if (data) {
            this.props.form.setFieldsValue({ txt_Inkey: data.tagname })
            this.setState({
                Inkey: data.tagname
            }, () => {
                this.GetProguctList();
                this.getCategory();
                this.getBrandListData();
            })
        } else {
            this.setState({
                Inkey: ""
            }, () => {
                this.GetProguctList();
                this.getCategory();
                this.getBrandListData();
            })
        }
    }

    //商品列表
    GetProguctList() {
        console.log(this.state.brandList)
        console.log(this.state.brandListid)
        $.ajax({
            url: `${config.JuseProduct}/products/list`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                inKey: this.state.Inkey,
                isPres: this.state.isdrugstatus,
                isRefrig: this.state.iscoldstorage,
                isEphe: this.state.isspecialdrug,
                saleStatus: this.state.salestatus || '1,2',
                categoryId: this.state.categoryid,
                brandId: this.state.brandListid,
            },
            success: res => {
                console.log('商品列表', res);
                if (res.code === 200) {
                    res.data.rows.forEach((item, index) => {
                        item.key = index + 1
                    })
                    this.setState({
                        productlist: res.data.rows,
                        productcount: res.data.count,
                    });
                }
            }
        });
    }
    //分类列表
    getCategory() {
        $.ajax({
            url: `${config.JuseProduct}/categories/getCategoriesTree`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            async: true,
            success: res => {
                console.log('分类列表', res);
                if (res.code === 200) {
                    const data = res.data;
                    const loop = list => {
                        list.forEach(item => {
                            item.key = item.categoryId
                            item.value = item.categoryId
                            item.label = item.categoryRename || item.categoryName
                            if (item.son) {
                                item.children = item.son
                                loop(item.children)
                            }
                        })
                    }
                    loop(res.data)
                    this.setState({
                        categoryData: res.data
                    })
                }
            }
        })
    }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.GetProguctList();
        });
    }

    //选择分类
    changeCategory(value) {
        this.setState({
            categoryid: value
        })
    }
    //类别的改变事件
    drugStatusChange(v) {
        this.setState({
            isdrugstatus: v
        });
    }
    //冷藏的改变事件
    coldstorageChange(v) {
        this.setState({
            iscoldstorage: v
        });
    }
    //特管的改变事件
    specialdrugChange(v) {
        this.setState({
            isspecialdrug: v
        });
    }
    //状态的改变事件
    salestatusChange(v) {
        this.setState({
            salestatus: v
        });
    }
    //品牌的改变事件
    changbrand(value) {
        console.log("品牌", value)
        this.setState({
            brandListid: value
        })
    }
    //搜索
    SearchProductListBtn() {
        const form = this.props.form;
        this.setState({
            pageindex: 1,
            Inkey: form.getFieldValue('txt_Inkey') ? form.getFieldValue('txt_Inkey') : ''
        }, () => {
            this.GetProguctList();
        });
    }
    //重置
    ResetBtn() {
        const form = this.props.form;
        form.resetFields();
        this.setState({
            pageindex: 1,
            categoryid: undefined,
            isdrugstatus: undefined,
            iscoldstorage: undefined,
            isspecialdrug: undefined,
            salestatus: undefined,
            Inkey: undefined,
            brandListid: undefined,
        }, () => {
            this.GetProguctList();
        });
    }

    //选择需要操作的商品
    selectProduct(productid, e) {
        const { selectproductid } = this.state;
        if (e.target.checked) {
            selectproductid.push(productid);
        } else {
            const index = selectproductid.indexOf(productid);
            selectproductid.splice(index, 1);
        }
        this.setState({
            selectproductid
        })
    }
    //商品(上/下架)
    ChangeProductStateManage(status, text) {
        const { selectproductid } = this.state;
        if (selectproductid.length > 0) {
            if (status === 1) { // 上架
                $.ajax({
                    url: `${config.JuseProduct}/products/onShelf`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        productId: selectproductid
                    },
                    success: res => {
                        console.log('上架', res)
                        if (res.code === 200) {
                            this.GetProguctList()
                        }
                    }
                })
            } else { // 下架
                $.ajax({
                    url: `${config.JuseProduct}/products/offShelf`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        productId: selectproductid
                    },
                    success: res => {
                        console.log('下架', res)
                        if (res.code === 200) {
                            this.GetProguctList()
                        } else {
                            message.error(res.mes)
                        }
                    }
                })
            }
        } else {
            message.warning('请选择需要操作的商品！');
        }
    }

    getBrandListData() {
        $.ajax({
            url: `${config.JuseProduct}/brand/list`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: 1000,
                page: 1,
                beactive: 'Y'
            },
            success: res => {
                if (res.code === 200) {
                    console.log('品牌列表', res.data.rows)
                    this.setState({
                        brandList: res.data.rows
                    })
                } else {
                    message.error('品牌列表加载失败，请返回重新操作', 2);
                }
            }
        });
    }
    render() {
        const brandOptions = this.state.brandList.map(item => {
            return <Option key={item.brandId} value={String(item.brandId)}>{item.brandName}</Option>
        })
        const { getFieldDecorator } = this.props.form;
        const columns = [
            {
                title: '序号',
                dataIndex: 'key',
                width: '6%',
                render: (text, record) => {
                    if (record.beactive == "N") {
                        return <div className='rowchangecolor'>{text}</div>;
                    } else {
                        return <div>{text}</div>;
                    }
                }
            },
            {
                title: '勾选',
                dataIndex: '',
                width: '6%',
                render: record => <Checkbox onChange={(e) => this.selectProduct(record.productId, e)}></Checkbox>
            },
            {
                title: '商品ID',
                dataIndex: 'productId',
                width: '6%',
                render: (text, record) => {
                    if (record.beactive == "N") {
                        return <div className='rowchangecolor'>{text}</div>;
                    } else {
                        return <div>{text}</div>;
                    }
                }
            },
            {
                title: '商品图片',
                dataIndex: '',
                width: '12%',
                render: (text, record) => {
                    return <img src={record.imageUrl + record.listImage} />
                }
            },
            {
                title: '商品信息',
                dataIndex: '',
                width: '25%',
                render: (text, record) => {
                    if (record.beactive == "N") {
                        return <div className='rowchangecolor'>
                            <div className='price-a'>
                                <p>{record.productName}</p>
                                <p>库存：{record.stock.totalStock} &nbsp;&nbsp;成本价：{record.cost}</p>
                            </div>
                        </div>;
                    } else {
                        return <div className='price-a'>
                            <p>{record.productName}</p>
                            <p>库存：{record.stock.totalStock} &nbsp;&nbsp;成本价：{record.cost}</p>
                        </div>;
                    }
                }
            }, {
                title: '分类',
                dataIndex: 'category.categoryName',
                width: '10%'
            },
            {
                title: '品牌',
                dataIndex: 'brandName',
                width: '7%',
            },
            {
                title: '商品价格',
                dataIndex: '',
                width: '16%',
                render: (text, record) => {
                    if (record.beactive == "N") {
                        return <div className='rowchangecolor'>
                            <div >
                                <p>零售价：{record.retailp}</p>
                                <p>商城价：{record.marketPrice}</p>
                            </div>
                        </div>;
                    } else {
                        return <div >
                            <p>零售价：{record.retailp}</p>
                            <p>商城价：{record.marketprice}</p>
                        </div>;
                    }
                }
            },
            {
                title: '商品状态',
                dataIndex: 'saleStatus',
                width: '6%',
                render: (text, record) => {
                    if (record.beactive == "N") {
                        return <div className='rowchangecolor'>{text === 1 ? "上架区" : "下架区"}</div>;
                    } else {
                        if (text === 1) {
                            return <div>上架区</div>;
                        } else if (text === 2) {
                            return <div className="saleoffcolor">下架区</div>;
                        }
                    }
                }
            },
            {
                title: '操作',
                dataIndex: '',
                width: '6%',
                render: (text, record) => {
                    return <Link to={'/goodsdetail/' + record.productId}>编辑</Link>
                }
            }
        ];
        return (
            <Form>
                <div className='goods-label' style={{ minWidth: 1250 }}>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>全部商品管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>

                        <div className='member-content-Search clearfix'>
                            <div className='addetd'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_Inkey')(
                                            <Input className='addetd-a-r' addonBefore="商品信息/品牌" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-bb indtner'>
                                <InputGroup compact>
                                    <Input addonBefore="分 类" />
                                    <TreeSelect
                                        style={{ width: 210 }}
                                        value={this.state.categoryid}
                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                        treeData={this.state.categoryData}
                                        placeholder="请选择"
                                        treeDefaultExpandAll
                                        onChange={(value) => this.changeCategory(value)}
                                    />
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-bb indtner'>
                                <InputGroup compact>
                                    <Input addonBefore="品 牌" />
                                    {/* <TreeSelect
                                        style={{ width: 210 }}
                                        value={this.state.categoryid}
                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                        treeData={this.state.categoryData}
                                        placeholder="请选择"
                                        treeDefaultExpandAll
                                        onChange={(value) => this.changeCategory(value)}
                                    /> */}
                                    <Select placeholder="请选择/搜索"
                                        showSearch
                                        style={{ width: 200 }}
                                        optionFilterProp="children"
                                        value={this.state.brandListid}
                                        onChange={(value) => this.changbrand(value)}
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                    >
                                        {brandOptions}
                                    </Select>
                                </InputGroup>
                            </div>
                        </div>
                        <div className='member-content-Search clearfix'>
                            {/*<div className='addetd addetd-a indtner'>*/}
                            {/*<InputGroup compact>*/}
                            {/*<Input addonBefore="类 别" />*/}
                            {/*<Select value={this.state.isdrugstatus} onChange={this.drugStatusChange.bind(this)} placeholder='请选择'>*/}
                            {/*<Option value="Y">处方药</Option>*/}
                            {/*<Option value="N">非处方药</Option>*/}
                            {/*</Select>*/}
                            {/*</InputGroup>*/}
                            {/*</div>*/}
                            {/*<div className='addetd addetd-a indtner'>*/}
                            {/*<InputGroup compact>*/}
                            {/*<Input addonBefore="冷 藏" />*/}
                            {/*<Select value={this.state.iscoldstorage} onChange={this.coldstorageChange.bind(this)} placeholder='请选择'>*/}
                            {/*<Option value="Y">冷藏</Option>*/}
                            {/*<Option value="N">非冷藏</Option>*/}
                            {/*</Select>*/}
                            {/*</InputGroup>*/}
                            {/*</div>*/}
                            {/*<div className='addetd addetd-a indtner'>*/}
                            {/*<InputGroup compact>*/}
                            {/*<Input addonBefore="特 管" />*/}
                            {/*<Select value={this.state.isspecialdrug} onChange={this.specialdrugChange.bind(this)} placeholder='请选择'>*/}
                            {/*<Option value="Y">特管药品</Option>*/}
                            {/*<Option value="N">非特管药品</Option>*/}
                            {/*</Select>*/}
                            {/*</InputGroup>*/}
                            {/*</div>*/}
                            <div className='addetd addetd-a indtner'>
                                <InputGroup compact>
                                    <Input addonBefore="状 态" />
                                    <Select value={this.state.salestatus} onChange={this.salestatusChange.bind(this)}>
                                        <Option value="1">已上架</Option>
                                        <Option value="2">已下架</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <Button type="primary" className='member-button' icon="search" onClick={this.SearchProductListBtn.bind(this)}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.ResetBtn.bind(this)}>重置</Button>
                        </div>

                        <div className='rowchangereds'>注：标红的行已删除</div>
                        <div className='clearfix'>
                            <Table
                                columns={columns}
                                dataSource={this.state.productlist}
                                pagination={false}
                                bordered
                                className='allgoods-table'
                            />
                            <div className='goods-label-tabletr'>
                                <Button className='goods-label-table-app' width={160} icon="plus" onClick={() => { window.location.hash = "/goodsdetail/0"; }}>发布新商品</Button>
                                <Button className='goods-label-table-app' width={105} icon="download" onClick={this.ChangeProductStateManage.bind(this, 2, '商品下架')}>商品下架</Button>
                                <Button className='goods-label-table-app' width={105} icon="upload" onClick={this.ChangeProductStateManage.bind(this, 1, '商品上架')}>商品上架</Button>
                            </div>
                        </div>
                        <div className='goods-label-let'>
                            <div className="floor-ppagi">
                                {
                                    this.state.productcount == 0 ?
                                        <p className="floor-ppagip">
                                            共{this.state.productcount}条记录
                                </p> :
                                        <p className="floor-ppagip">
                                            当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.productcount ? this.state.pagesize * this.state.pageindex : this.state.productcount}条记录，
                                    共{this.state.productcount}条记录
                                </p>
                                }
                                <Pagination current={this.state.pageindex} total={this.state.productcount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        )
    }
}

const Allgoods = Form.create()(RegForm);
export default Allgoods;